<?php
// +----------------------------------------------------------------------
// 管理员
// +----------------------------------------------------------------------
namespace app\admin\controller;
use app\admin\controller\Base;
use think\Validate;
class AdminUser extends Base
{
	//管理员列表
    public function index()
    {
        $where = array();
        $where['is_del'] = 0;
        $name = $this->request->param('name');
        if ($name){
            $where['admin_name'] = array('LIKE', '%'.$name.'%');
        }
        $list = model('AdminUser')->where($where)->order('admin_id asc')->paginate(15);
        foreach ($list as $k=>$v){
            $group= $v->admingroups()->wherePivot('w_admin_id',$v['admin_id'])->column('group_name');
            $list[$k]['group']= implode(',',$group);
        }

        $page = $list->render();
        $this->assign('list', $list);
        $this->assign('page', $page);
        return $this->fetch();
    }
    //添加管理员
    public function adminForm()
    {
    	$admin_id = $this->request->param('admin_id');
    	$admin = model('AdminUser')->get($admin_id);
        $this->assign('admin', $admin);
        //角色
        $check_group=[];
        if(!empty($admin)){
            $check_groups=$admin->admingroups;
            foreach($check_groups as $g){
                // 获取中间表数据
                $check_group=$g->pivot->where('w_admin_id',$admin_id)->column('w_group_id');
            }
        }
        $this->assign('check_group', $check_group);

        $where['is_del'] = 0;
    	$group= model('AdminGroup')->where($where)->column('group_id,group_name');
        $this->assign('group', $group);
    	return $this->fetch();
    }
    //删除管理员
    public function delAdmin()
    {
        $users=model('AdminUser');
    	$data['admin_id'] = $this->request->param('admin_id');
    	$data['is_del'] = 1;
        $user = $users->update($data);
        $user->admingroups()->detach();
    	if ($user){
    		$this->create_adminlog('删除管理员ID：'.$data['admin_id'].'');
    		echo json_encode(['status'=>1,'msg'=>'删除成功']);exit();
    	}else{
    		echo json_encode(['status'=>0,'msg'=>'删除失败']);exit();
    	}
    }
    //保存新增管理员
    public function saveAdmin()
    {
        $post=$this->request->param();
        $post['department_id'] = empty($_POST['department_id'])?'':implode(',', $_POST['department_id']);
        $admin_id=$post['admin_id'];
        if($admin_id>0){
            $attr_status=$this->saveEdit($post);
        }else{
            $attr_status=$this->saveAdd($post);
        }

    	if ($attr_status){
    		$this->create_adminlog('保存 '.$post['admin_name'].' >'.$post['admin_name'].' 管理员');
    		echo json_encode(['status'=>1,'msg'=>'保存成功']);exit();
    	}else{
    		echo json_encode(['status'=>0,'msg'=>'保存失败']);exit();
    	}
    }

    /**
     * 新增操作
     */
    public function saveAdd($post){
        $users=model('AdminUser');

        $rule = [
                'admin_name'  => 'require|max:255|unique:AdminUser',
                'admin_password'  => 'require|min:6|max:100',
                're_admin_password'  => 'require|confirm:admin_password',
                'group'  => 'require'
            ];

        $msg = [
                'admin_name.require' => '管理员账号不能为空',
                'admin_name.max' => '管理员账号长度不能超过255个字符',
                'admin_name.unique' => '管理员账号已存在',
                'admin_password' => '账号密码请输入0-127之间',
                're_admin_password' => '密码不一致',
                'group.require' => '请选择角色组',
            ];

        $validate = new Validate($rule, $msg);
        if (!$validate->check($post)){
            echo json_encode(['status'=>0,'msg'=>$validate->getError()]);exit();
        }
        $data['admin_id']=$post['admin_id'];
        $data['admin_name']=$post['admin_name'];
        $data['admin_password']=md5($post['admin_password']);
        $data['realname']=$post['realname'];
        $data['mobile']=$post['mobile'];
        $data['email']=$post['email'];
        $data['w_department_ids'] = empty($post['department_id'])?'':$post['department_id'];
        $data['ctime']=time();

        $user=$users->create($data);
        $attr_status = $user->admingroups()->attach($post['group']);

        return $attr_status;
    }
    /**
     * 编辑操作
     */
    public function saveEdit($post){
        $users=model('AdminUser');
        $admin_id=$post['admin_id'];
        $rule = [
                'admin_name'  => 'require|max:255|unique:AdminUser,admin_name,'.$admin_id.',admin_id',
                'group'  => 'require'
            ];
        $msg = [
                'admin_name.require' => '管理员账号不能为空',
                'admin_name.max' => '管理员账号长度不能超过255个字符',
                'admin_name.unique' => '管理员账号已存在',
                'group.require' => '请选择角色组',
            ];
        if(!empty($post['admin_password'])){
            $rule['admin_password']='min:6|max:100';
            $rule['re_admin_password']='require|confirm:admin_password';

            $msg['admin_password']='账号密码请输入0-127之间';
            $msg['re_admin_password']='密码不一致';
            $data['admin_password']=md5($post['admin_password']);
        }

        $validate = new Validate($rule, $msg);
        if (!$validate->check($post)){
            echo json_encode(['status'=>0,'msg'=>$validate->getError()]);exit();
        }


        $data['admin_id']=$post['admin_id'];
        $data['admin_name']=$post['admin_name'];
        $data['realname']=$post['realname'];
        $data['mobile']=$post['mobile'];
        $data['email']=$post['email'];
        $data['w_department_ids'] = empty($post['department_id'])?'':$post['department_id'];
        $user=$users->update($data);
        $user->admingroups()->detach();
        $attr_status = $user->admingroups()->attach($post['group']);

        return $attr_status;

    }

    /**
     * 管理员详情
     */
    public function userInfo(){
        $admin_id = session('user.admin_id');
        $admin = model('AdminUser')->get($admin_id);
        $this->assign('admin', $admin);

        $role=$admin->admingroups()->wherePivot('w_admin_id',$admin_id)->field('group_id,group_name')->select();
        $this->assign('role', $role);

        //拥有权限
        $role_id=array_column(json_decode(json_encode($role),true),'group_id');
        $power=Model('AdminGroup')->get(1);
        $powers=$power->menus()->wherePivot('w_group_id','in',$admin_id)->field('menu_id,menu_name,parent_id')->select();

        $powers=model('AdminGroup')->getSubTreeb($powers);
        $this->assign('powers', $powers);

        return $this->fetch('admin_info');
    }
    /**
     * 管理员基础信息编辑
     */
    public function userEdit(){
        $post=$this->request->param();
        $users=model('AdminUser');
        $admin_id=$post['admin_id'];
        $rule = [
            'admin_name'  => 'require|max:255|unique:AdminUser,admin_name,'.$admin_id.',admin_id',
        ];
        $msg = [
            'admin_name.require' => '管理员账号不能为空',
            'admin_name.max' => '管理员账号长度不能超过255个字符',
            'admin_name.unique' => '管理员账号已存在',
        ];

        $validate = new Validate($rule, $msg);
        if (!$validate->check($post)){
            echo json_encode(['status'=>0,'msg'=>$validate->getError()]);exit();
        }


        $data['admin_id']=$post['admin_id'];
        $data['admin_name']=$post['admin_name'];
        $data['realname']=$post['realname'];
        $data['mobile']=$post['mobile'];
        $data['email']=$post['email'];

        $attr_status=$users->update($data);
        if ($attr_status){
            $this->create_adminlog('管理员 '.$post['admin_name'].'编辑个人信息');
            echo json_encode(['status'=>1,'msg'=>'保存成功']);exit();
        }else{
            echo json_encode(['status'=>0,'msg'=>'保存失败']);exit();
        }

    }
    /**
     * 管理员修改密码
     */
    public function editPass(){
        $admin_id = session('user.admin_id');
        $admin = model('AdminUser')->get($admin_id);
        $this->assign('admin', $admin);
        return $this->fetch('admin_password');
    }
    /**
     * 修改密码
     */
    public function savePass(){
        $post=$this->request->param();
        $rule = [
            'admin_password'  => 'require',
            'new_password'  => 'require|min:6|max:180',
            're_admin_password'  => 'require|confirm:new_password',
        ];

        $msg = [
            'admin_password' => '账号密码必填',
            'new_password' => '新账号密码长度在6-180个字符',
            're_admin_password' => '密码不一致',
        ];

        $validate = new Validate($rule, $msg);
        if (!$validate->check($post)){
            echo json_encode(['status'=>0,'msg'=>$validate->getError()]);exit();
        }

        $admin_id = session('user.admin_id');
        $admin = model('AdminUser')->get($admin_id);
        if(md5($post['admin_password'])!==$admin['admin_password']){
            echo json_encode(['status'=>0,'msg'=>'密码错误']);exit();
        }
        $data['admin_id']=$admin_id;
        $data['admin_password']=md5($post['new_password']);
        $attr_status = model('AdminUser')->update($data);
        if ($attr_status){
            $this->create_adminlog($post['admin_name'].'管理员 >'.'修改密码 ');
            session(null);
            cookie(null);
            echo json_encode(['status'=>1,'msg'=>'保存成功','url'=>url('Login/index')]);exit();
        }else{
            echo json_encode(['status'=>0,'msg'=>'保存失败']);exit();
        }
    }





}
